package com.ruoyi.web.controller.campus;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.campus.domain.SecurityGuard;
import com.ruoyi.campus.domain.PatrolPoint;
import com.ruoyi.campus.service.ISecurityGuardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.file.FileUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.ArrayList;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DateUtil;
import com.ruoyi.common.utils.StringUtils;

/**
 * 安全员信息Controller
 * 
 * @author ruoyi
 * @date 2025-06-29
 */
@Api(tags = "安全员信息管理")
@RestController
@RequestMapping("/campus/guard")
public class SecurityGuardController extends BaseController
{

    @Autowired
    private ISecurityGuardService securityGuardService;



    /**
     * 查询安全员信息列表
     */
    @ApiOperation("查询安全员信息列表")
    @RequiresPermissions("campus:guard:list")
    @GetMapping("/list")
    public TableDataInfo list(SecurityGuard securityGuard)
    {
        startPage();
        List<SecurityGuard> list = securityGuardService.selectSecurityGuardList(securityGuard);
        return getDataTable(list);
    }

    /**
     * 获取可绑定的安全员列表（下拉选择用）
     */
    @ApiOperation("获取可绑定的安全员列表(不带分页)")
    @RequiresPermissions("campus:guard:list")
    @GetMapping("/bindableList")
    public AjaxResult bindableList()
    {
        SecurityGuard securityGuard = new SecurityGuard();
        List<SecurityGuard> list = securityGuardService.selectSecurityGuardList(securityGuard);
        return AjaxResult.success(list);
    }

    /**
     * 根据安全员ID查询绑定的点位列表
     */
    @ApiOperation("根据安全员ID查询绑定的点位列表")
    @RequiresPermissions("campus:guard:list")
    @GetMapping("/points/{guardId}")
    public AjaxResult getPatrolPointsByGuardId(@PathVariable("guardId") Long guardId)
    {
        // 校验安全员ID不能为空
        if (guardId == null)
        {
            return AjaxResult.error("安全员ID不能为空");
        }
        
        // 校验安全员是否存在
        SecurityGuard existGuard = securityGuardService.selectSecurityGuardByGuardId(guardId);
        if (existGuard == null)
        {
            return AjaxResult.error("安全员不存在");
        }
        
        List<PatrolPoint> list = securityGuardService.selectPatrolPointsByGuardId(guardId);
        return AjaxResult.success(list);
    }

    /**
     * 导出安全员信息列表
     */
    @ApiOperation("导出安全员信息列表")
    @RequiresPermissions("campus:guard:export")
    @Log(title = "安全员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(SecurityGuard securityGuard)
    {
        List<SecurityGuard> list = securityGuardService.selectSecurityGuardList(securityGuard);
        ExcelUtil<SecurityGuard> util = new ExcelUtil<SecurityGuard>(SecurityGuard.class);
        return util.exportExcel(list, "安全员信息数据");
    }



    /**
     * 新增保存安全员信息
     */
    @ApiOperation("新增保存安全员信息")
    @RequiresPermissions("campus:guard:add")
    @Log(title = "安全员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult addSave(@RequestBody SecurityGuard securityGuard)
    {
        return toAjax(securityGuardService.insertSecurityGuard(securityGuard, getLoginName()));
    }

    /**
     * 修改安全员信息
     */
    @ApiOperation("获取安全员信息")
    @RequiresPermissions("campus:guard:get")
    @GetMapping("/{guardId}")
    public AjaxResult get(@PathVariable("guardId") Long guardId)
    {
        return AjaxResult.success(securityGuardService.selectSecurityGuardByGuardId(guardId));
    }

    /**
     * 修改保存安全员信息
     */
    @ApiOperation("修改保存安全员信息")
    @RequiresPermissions("campus:guard:edit")
    @Log(title = "安全员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult editSave(@RequestBody SecurityGuard securityGuard)
    {
        // 校验安全员ID不能为空
        if (securityGuard.getGuardId() == null)
        {
            return AjaxResult.error("安全员ID不能为空");
        }
        
        // 校验安全员是否存在
        SecurityGuard existGuard = securityGuardService.selectSecurityGuardByGuardId(securityGuard.getGuardId());
        if (existGuard == null)
        {
            return AjaxResult.error("安全员不存在，无法修改");
        }
        
        return toAjax(securityGuardService.updateSecurityGuard(securityGuard, getLoginName()));
    }

    /**
     * 删除安全员信息
     */
    @ApiOperation("删除安全员信息")
    @RequiresPermissions("campus:guard:remove")
    @Log(title = "安全员信息", businessType = BusinessType.DELETE)
    @DeleteMapping( "/{ids}")
    public AjaxResult remove(@PathVariable String ids)
    {
        // 校验ids不能为空
        if (ids == null || ids.trim().isEmpty())
        {
            return AjaxResult.error("删除的安全员ID不能为空");
        }
        
        // 校验分割后的ID数组不能为空
        String[] idArray = ids.split(",");
        if (idArray.length == 0)
        {
            return AjaxResult.error("删除的安全员ID不能为空");
        }
        
        // 校验每个ID不能为空
        for (String id : idArray)
        {
            if (id == null || id.trim().isEmpty())
            {
                return AjaxResult.error("安全员ID格式不正确，不能包含空值");
            }
        }
        
        return toAjax(securityGuardService.deleteSecurityGuardByGuardIds(ids));
    }

    /**
     * 导入安全员信息
     */
    @Log(title = "安全员管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("campus:guard:import")
    @PostMapping("/importData")
    @ApiOperation("导入安全员信息")
    public AjaxResult importData(@RequestParam("file") MultipartFile file, @RequestParam(value = "updateSupport", defaultValue = "false") boolean updateSupport) throws Exception
    {
        // 校验文件不能为空
        if (file == null || file.isEmpty())
        {
            return AjaxResult.error("上传文件不能为空");
        }

        // 校验文件格式
        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")))
        {
            return AjaxResult.error("请上传Excel格式文件(.xlsx或.xls)");
        }

        // 使用自定义Excel解析方法
        List<SecurityGuard> securityGuardList = parseSecurityGuardExcel(file.getInputStream());
        String operName = getLoginName();
        String message = securityGuardService.importSecurityGuard(securityGuardList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 下载安全员导入模板
     */
    @PostMapping("/importTemplate")
    @ApiOperation("下载安全员导入模板")
    public void importTemplate(HttpServletResponse response) throws Exception
    {
        // 直接下载resources目录下的模板文件
        String fileName = "安全员管理-导入模板.xlsx";

        try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName)) {
            if (inputStream == null) {
                throw new Exception("模板文件不存在: " + fileName);
            }

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);

            // 直接从输入流复制到输出流
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
            response.getOutputStream().flush();
        }
    }

    /**
     * 解析安全员Excel文件
     * 数据从第三行开始，字段分别是：安全员姓名（必填）、所属部门名称（必填）、办公室电话、手机号（必填）、微信号
     */
    private List<SecurityGuard> parseSecurityGuardExcel(InputStream inputStream) throws Exception
    {
        List<SecurityGuard> securityGuardList = new ArrayList<>();
        Workbook workbook = null;

        try {
            // 尝试创建工作簿
            try {
                workbook = new XSSFWorkbook(inputStream);
            } catch (Exception e) {
                inputStream.reset();
                workbook = new HSSFWorkbook(inputStream);
            }

            Sheet sheet = workbook.getSheetAt(0);

            // 从第三行开始读取数据（索引为2）
            for (int i = 2; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }

                // 检查是否为空行
                boolean isEmptyRow = true;
                for (int j = 0; j < 5; j++) {
                    Cell cell = row.getCell(j);
                    if (cell != null && StringUtils.isNotEmpty(getCellValue(cell))) {
                        isEmptyRow = false;
                        break;
                    }
                }

                if (isEmptyRow) {
                    continue;
                }

                SecurityGuard securityGuard = new SecurityGuard();

                // 第1列：安全员姓名（必填）
                Cell nameCell = row.getCell(0);
                if (nameCell != null) {
                    securityGuard.setName(getCellValue(nameCell));
                }

                // 第2列：所属部门名称（必填）
                Cell deptNameCell = row.getCell(1);
                if (deptNameCell != null) {
                    securityGuard.setDeptName(getCellValue(deptNameCell));
                }

                // 第3列：办公室电话
                Cell officePhoneCell = row.getCell(2);
                if (officePhoneCell != null) {
                    securityGuard.setOfficePhone(getCellValue(officePhoneCell));
                }

                // 第4列：手机号（必填）
                Cell phoneNumberCell = row.getCell(3);
                if (phoneNumberCell != null) {
                    securityGuard.setPhoneNumber(getCellValue(phoneNumberCell));
                }

                // 第5列：微信号
                Cell wechatIdCell = row.getCell(4);
                if (wechatIdCell != null) {
                    securityGuard.setWechatId(getCellValue(wechatIdCell));
                }

                securityGuardList.add(securityGuard);
            }
        } finally {
            if (workbook != null) {
                workbook.close();
            }
        }

        return securityGuardList;
    }

    /**
     * 获取单元格值
     */
    private String getCellValue(Cell cell)
    {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 处理数字，避免科学计数法
                    double numericValue = cell.getNumericCellValue();
                    if (numericValue == (long) numericValue) {
                        return String.valueOf((long) numericValue);
                    } else {
                        return String.valueOf(numericValue);
                    }
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}
